<template>
  <div class="uplaodBoxs">
    <!-- <div @click="j">跳转</div> -->
    <a-spin tip="上传中。。。" class="spin-content" :spinning="uploading">
      <div class="ant-upload-select-text-box" style="padding-top: 24px">
        <a-upload ref="upload" accept=".xls, .xlsx, .xlsm" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
          <img :src="uploadImg" style="width: 139px; height: 106px" />
          <div class="ant-modal-body">
            <div style="font-size: 14px; color: #666"><span style="color: #6a66f6">将文件拖到此处</span>或点击上传上传考勤表</div>
            <!-- <div style="font-size: 12px;color: #999">
            (文件大小不超过5M)
          </div> -->
            <a-button icon="plus" type="primary" style="margin-top: 10px"> 添加文件 </a-button>
          </div>
        </a-upload>
      </div>
    </a-spin>
    <div class="tipBox">
      <a-row style="color: #252525; font-size: 16px; font-weight: 500; padding-bottom: 10px"> 温馨提示 </a-row>
      <a-row>
        <a-col :span="12">
          <div>
            请先下载模板，根据模板填写信息后再进行上传。
            <span @click="download" style="font-size: 12px; color: #6a66f6; cursor: pointer"> 点击下载模板 </span>
          </div>
          <div>1、支持wps，excel2003以上版本文件，支持xlsx格式；</div>
          <div>2、模板文件大小不得超过5M，单次导入上传数据不得超过2000条；</div>
          <div>3、请不要上传加密或带宏的文件，不然将导致上传错误；</div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script>
import { getToken } from "xqjr-module-auth";
import axios from "axios";
import qs from "qs";
import { getQueryTemplateInfoPage } from "../api";

export default {
  data() {
    return {
      id: "",
      data: {},
      fileList: [],
      uploading: false,
      selectedRowKeys: [],
      headers: {},
      file: "",
      action: "",
      uploadImg: require("@/assets/img/uploadImg.png"),
      attendanceSallaryTemplateId: ""
    };
  },
  computed: {},
  created() {
    this.headers = {
      token: getToken(),
      "Content-Type": "multipart/form-data"
    };
    this.id = this.$store.state.hr.companyId;
    this.action = `/salary/api/v1/empFixedSalaries/import?companyId=${this.id}&force=false`;
    this.onGetQueryTemplateInfoPage();
  },
  methods: {
    async onGetQueryTemplateInfoPage() {
      try {
        this.spinning = true;
        const { data } = await getQueryTemplateInfoPage({
          configurationName: "工种",
          pageNo: 1,
          pageSize: 1,
          companyId: this.$store.state.hr.companyId,
          "orders[0].property": "gmtCreate",
          "orders[0].desc": true
        });
        this.attendanceSallaryTemplateId = data.entities[0].attendanceSallaryTemplateId;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message.error("最多只能上传一个");
        return false;
      }
      this.fileList = [...this.fileList, file];
      if (this.fileList && this.fileList.length > 0) {
        const { fileList } = this;
        const formData = new FormData();
        const year = this.$route.query.time.split("-")[0];
        const month = this.$route.query.time.split("-")[1];
        fileList.forEach(file => {
          formData.append("file", file);
          formData.append("companyId", this.id);
          formData.append("year", year);
          formData.append("month", month);
          formData.append("tempId", this.attendanceSallaryTemplateId);
        });
        this.uploading = true;
        axios({
          url: `/hr/api/v1/attendanceDataTemps/newImportFile`,
          method: "post",
          data: formData,
          headers: this.headers
        }).then(res => {
          this.handleSuccess(res.data);
          this.uploading = false;
        });
      } else {
        this.handleUploadError();
      }
      return false;
    },
    handleUploadError() {
      // this.$message.warning("没有文件");
    },
    // handleFailClose() {
    //   this.dialogFailVisible = false;
    // },
    handleSuccess(res) {
      var that = this;

      if (res.code === 200) {
        if (res.data.attendanceDataRecordId) {
          this.$confirm({
            okText: "确定",
            title: `上传成功`,
            onOk() {
              const json = {
                recordId: res.data.attendanceDataRecordId,
                tempId: that.attendanceSallaryTemplateId,
                allDataCount: res.data.allDataCount,
                errorDataCount: res.data.errorDataCount
              };
              that.$emit("onAction", 1, json);
            }
          });
        } else {
          this.$notification["error"]({
            message: "error",
            description: "上传失败"
          });
        }
      } else if (res.data === null) {
        this.$confirm({
          okText: "确定",
          title: res.msg,
          cancelButtonProps: false
        });
      } else {
        this.$notification["error"]({
          message: "error",
          description: res.msg || "上传失败"
        });
      }
      setTimeout(() => {
        this.reset();
      }, 2000);
    },
    j() {
      this.$emit("onAction", 1, {
        type: "preview",
        recordId: "55F62AF756C64E079A65AC198ECD2F18",
        tempId: this.attendanceSallaryTemplateId,
        allDataCount: 100,
        errorDataCount: 10
      });
    },
    goback() {
      this.$router.go(-1);
    },
    download() {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        // templateName: "allEmployeeSalary.xlsx"
      };

      axios({
        url: `/hr/api/v1/attendanceSallaryTemplates/downloadTemplate`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "GET",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "考勤导入模板.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },
    reset() {
      this.fileList = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.exportTitle {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #252525;
}
.left2 {
  z-index: 3;
  left: 50px;
  position: absolute;
  color: #595959;
  font-size: 14px;
}
.tipBox {
  line-height: 18px;
  background: #faf9f9;
  border-radius: 4px;
  font-size: 12px;
  color: #595959;
  margin: 0 24px;
  width: calc(100% - 48px) !important;
  padding: 12px;
}
.ant-upload-select-text-box {
  border: 1px dashed #b8b8b8;
  background: #fff;
  margin: 24px;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  padding: 12px;
}
.ant-upload-select-text-box ::v-deep .ant-upload-list {
  display: none;
}
.ant-upload-list-item-name {
  text-align-last: left;
}

.anticon-upload {
  font-size: 40px;
}

.ant-modal-body {
  line-height: 24px;

  em {
    color: #6a66f6;
    font-style: normal;
  }
}
</style>
